package com.example.recyclerviewtest;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class AnimalAdapter extends RecyclerView.Adapter<AnimalAdapter.ViewHolder>{

    private List<Animal> animals;


    public AnimalAdapter(List<Animal> animals) {
        this.animals = animals;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        viewHolder.imgview.setOnClickListener(
                item -> {
                    int adapterPosition = viewHolder.getAdapterPosition();
                    Animal animal = animals.get(adapterPosition);
                    Toast.makeText(item.getContext(), "点击的是" + animal.getName(), Toast.LENGTH_SHORT).show();
                }
        );
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Animal animal = animals.get(position);
        holder.tvName.setText(animal.getName());
        holder.tvEnglish.setText(animal.getEnglishName());
        holder.imgview.setImageResource(animal.getImageId());
    }

    @Override
    public int getItemCount() {
        return animals.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        ImageView imgview;
        TextView tvName;
        TextView tvEnglish;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            imgview = itemView.findViewById(R.id.imgview);
            tvName = itemView.findViewById(R.id.tvName);
            tvEnglish = itemView.findViewById(R.id.tvEnglishName);
        }
    }


}
